<!--
 * @Date: 2024-09-24 13:54:03
 * @Author: LiSong
 * @LastEditors: LiSong
 * @LastEditTime: 2025-01-14 20:08:24
 * @Description: 表单管理（新）
-->
<template>
  <RkContainer :="containerAttrs">
    <template #aside>
      <div class="form-aside-wrap">
        <div class="form-aside-header">
          <el-button type="primary">新增</el-button>
          <el-button type="primary">修改</el-button>
          <el-button type="danger">删除</el-button>
        </div>
        <div class="form-aside-body">
          <RkTreePanel
            :="treeAttrs"
            @currentChange="treeCurrentChange"
          />
        </div>
      </div>
    </template>
    <template #main>
      <div class="form-aside-wrap">
        <div class="form-aside-header content-right">
          <el-button v-for="(item, index) in toolbarEnums"
            :key="index" :type="item.type"
            @click="toolbarOperate(item)"
          >{{ item.name }}</el-button>
        </div>
        <div class="form-aside-body table">
          <rk-grid
            ref="tableRef"
            :="tableAttrs"
            :params="tableParams"
            :columns="tableColumns"
          >
            <template #toolbar_right>
              <el-select
                v-model="tableParams.status"
                placeholder="请选择状态"
                class="mr-12"
                clearable
                style="width: 200px"
                @change="handleSearch"
              >
                <el-option
                  v-for="item in COMMON_STOP_OPEN_ENUMS.options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-input
                v-model="tableParams.keyWords"
                style="width: 250px"
                clearable
                placeholder="请输入名称/编码"
                @change="handleSearch"
              />
            </template>
            <template #operation="{row}">
              <el-button
                v-for="(item, index) in rowFuncEnums"
                :key="index" :type="item.type" link
                @click.stop="tableRowOperate(item, row)">
                {{ item.name }}
              </el-button>
            </template>
          </rk-grid>
        </div>
      </div>
      <!-- <FormDesignDrawer ref="formDesignerRef" /> -->
    </template>
  </RkContainer>
</template>

<script setup>
import { ElMessage } from 'element-plus';
import { reactive, ref } from 'vue';

import { RkTreePanel } from '@/components/tree';
import { RkConfirmBox } from '@/components/message-box/index.js';

import { useFormListApi } from '@/api';
import { COMMON_STOP_OPEN_ENUMS } from '@/enums/enums-common.js';

// 布局组件的属性
const containerAttrs = reactive({
  isHeader: false,
  isFooter: false
})

// 树结构属性
const treeAttrs = reactive({
  treeTitle: '表单类型',
  serverConfig: {
    url: '/dict/getFromProcessClassifyByType',
    params: { type: 1 }, // type: 1-表单 2-流程
  }
})
// 树结构数据集
const treeState = reactive({
  activeData: null,
  activeNode: {},
})
/**
 * 树结构选中改变方法
 * 
 * @param data 选中数据
 * @param node 选中节点
 */
const treeCurrentChange = (data, node) => {
  treeState.activeData = data
  treeState.activeNode = node
  handleSearch()
}

// 功能栏的按钮枚举
const toolbarEnums = {
  XJ: { code: 'XJ', name: '新建', type: 'primary' },
  QY: { code: 'QY', name: '启用', type: 'default', status: 1, func: useFormListApi().updateStatus },
  TY: { code: 'TY', name: '停用', type: 'default', status: 0, func: useFormListApi().updateStatus },
  DE: { code: 'DE', name: '删除', type: 'danger', status: 1, func: useFormListApi().delPrdFormInfo },
}

/**
 * 功能栏的通用操作方法
 * 
 * @param item 枚举项
 */
const toolbarOperate = (item) => {
  switch(item.code) {
    case toolbarEnums.XJ.code:
      handleAdd()
      break;
    case toolbarEnums.QY.code:
      handleMulti(item)
      break;
    case toolbarEnums.TY.code:
      handleMulti(item)
      break;
    case toolbarEnums.DE.code:
      handleMulti(item)
      break;
    default:
      break;
  }
}
/**
 * 新建方法
 */
const handleAdd = () => {
  const { activeData } = treeState
  if (activeData && activeData.children && activeData.children.length) {
    ElMessage.warning('请选择一个底级节点再进行操作！')
    return
  }
  formDesignerRef.value.handleOpen({
    type: 'add',
    formType: activeData.code,
    formTypeName: activeData.name
  })
}
/**
 * 针对多选操作通用方法
 * 
 * @param item 功能枚举项
 */
const handleMulti = (item) => {
  const selectRows = tableRef.value.getCheckboxRecords();
  if (!(selectRows && selectRows.length)) {
    ElMessage.warning('请至少选择一条数据进行操作！')
    return
  }
  const { name, status, func } = item
  RkConfirmBox({
    title: '提示',
    content: `您确定要${name}吗？`,
    onSubmit: async () => {
      const params = {
        status,
        formIds: selectRows.map((item) => item.formId).join(','),
      }
      const result = await func(params)
      const { code, msg } = result;
      if (code === 200) {
        ElMessage.success(`${name}成功！`)
        handleSearch()
      } else {
        ElMessage.error(msg)
      }
    },
    onCancel: () => {},
  })
}

// 表格Ref对象
const tableRef = ref(null)
const formDesignerRef = ref()
// 表格属性
const tableAttrs = reactive({
  title: '表单列表',
  dataUrl: '/prdFormInfo/queryPrdFormInfoPageList',
  keyField: 'formId',
  autoLoad: false,
  boxConfig: true
})
// 表格参数
const tableParams = reactive({
  status: undefined,
  formType: undefined,
	keyWords: undefined,
})
// 表格字段
const tableColumns = reactive([
  {
		field: 'status',
		title: '状态',
		width: 120,
		align: 'center',
		cellRender: { name: 'enumsRender', enumName: 'COMMON_STOP_OPEN_ENUMS', isTag: true },
	},
  { field: 'name', title: '名称', align: 'left',width: 350,  headerAlign: 'center' },
	{ field: 'code', title: '编码', align: 'left', width: 300, headerAlign: 'center' },
  { field: 'createTime', title: '创建时间', width: 200, showOverflow: true, align: 'center' },
	{ field: 'operation', title: '操作', width: 150, showOverflow: true, align: 'center', slots: { default: 'operation' } },
])
/**
 * 表格的查询方法
 */
const handleSearch = () => {
  const { activeData } = treeState
  if (!activeData) return
  tableParams['formType'] = activeData.code
  nextTick(() => { tableRef.value.searchEvent() })
}
// 行操作的枚举数据
const rowFuncEnums = {
  SJ: { code: 'SJ', name: '设计', type: 'primary' },
  YL: { code: 'YL', name: '预览', type: 'primary' },
  FZ: { code: 'FZ', name: '复制', type: 'primary' },
}
/**
 * 行操作的通用方法
 *
 * @param param 操作的枚举数据
 * @param row 操作的行数据
 */
const tableRowOperate = ({ code }, row) => {
  switch(code) {
    case rowFuncEnums.SJ.code:
      formDesignerRef.value.handleOpen({
        type: 'edit',
        code: row.code,
        formId: row.formId,
        formType: row.formType,
        formTypeName: row.formTypeName
      })
      break;
    case rowFuncEnums.YL.code:
      formPreviewerRef.value.handleOpen({
        code: row.code,
        type: 'preview',
        formId: row.formId,
        formCode: row.code,
        formType: row.formType,
      })
      break;
    case rowFuncEnums.FZ.code:
      handleFormCopy(row)
      break;
    default:
      break;
  }
}
/**
 * 复制操作
 * 
 * @param param 参数 { formId, name }
 */
const handleFormCopy = async ({ formId, name }) => {
  try {
    const result = await useFormListApi().copyPrdFormInfo({ formId })
    const { code, msg } = result;
    if (code === 200) {
      ElMessage.success(`复制[${name}]成功！`)
      handleSearch()
    }  else {
      ElMessage.error(msg)
    }
  } catch(error) {
    console.error('复制失败！', error)
  }
  
}
</script>

<style lang="scss" scoped>
.form-aside-wrap {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.form-aside-header {
  display: flex;
  align-items: center;
  height: 50px;
  padding: 5px;
  border-bottom: 1px solid #dadada;
  &.content-right {
    justify-content: right;
  }
}
.form-aside-body {
  &.table {
    padding-top: .6rem;
  }
  flex: 1;
  min-height: 100px;
  :deep(.vxe-toolbar) {
    padding-top: 0;
  }
}
</style>